package io.webfolder.cdp.channel;

import static javax.websocket.ClientEndpointConfig.Builder.create;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.websocket.DeploymentException;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import io.webfolder.cdp.exception.CdpException;
import io.webfolder.cdp.session.MessageHandler;
import io.webfolder.cdp.session.SessionFactory;

public class StandardWebSocketFactory implements ChannelFactory {

	private final WebSocketContainer webSocketContainer;

	public StandardWebSocketFactory(WebSocketContainer webSocketContainer) {
		this.webSocketContainer = webSocketContainer;
	}

	@Override
	public Channel createChannel(Connection connection, SessionFactory factory, MessageHandler handler) {
		String url = ((WebSocketConnection) connection).getUrl();
		URI uri;
		try {
			uri = new URI(url);
		} catch (URISyntaxException e) {
			throw new CdpException(e);
		}
		try {
			StandardWebSocketListener listener = new StandardWebSocketListener(factory, handler);
			Session session = webSocketContainer.connectToServer(listener, create().build(), uri);
			session.addMessageHandler(listener);
			return new StandardWebSocketChannel(session);
		} catch (DeploymentException | IOException e) {
			throw new CdpException(e);
		}
	}
}
